package com.tripwego.client.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.tripwego.client.ClientFactory;
import com.tripwego.client.common.TwgConstants;
import com.tripwego.client.event.InitListTripEvent;
import com.tripwego.client.model.TripModel;
import com.tripwego.client.place.HomePlace;
import com.tripwego.client.place.VoyagePlace;
import com.tripwego.client.service.TripDao;
import com.tripwego.client.service.TripDaoAsync;
import com.tripwego.client.ui.pageAccueil.IHomeView;
import com.tripwego.shared.dto.TripDto;

public class HomeActivity extends AbstractActivity implements IHomeView.Presenter {

	private ClientFactory clientFactory;

	private IHomeView homeView;
	private static EventBus eventBus;

	private final TripDaoAsync tripDao = GWT.create(TripDao.class);

	public HomeActivity(HomePlace place, ClientFactory clientFactory) {
		this.clientFactory = clientFactory;
	}

	/**
	 * Invoked by the ActivityManager to start a new Activity
	 */
	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		homeView = clientFactory.getHomeView();
		this.eventBus = eventBus;

		homeView.setPresenter(this);
		homeView.setEventBus(eventBus);

		panel.setWidget(homeView.asWidget());
	}

	/**
	 * Ask user before stopping this activity
	 */
	@Override
	public String mayStop() {
		return null;
	}

	/**
	 * Navigate to a new Place in the browser
	 */
	public void goTo(Place place) {
		clientFactory.getPlaceController().goTo(place);
	}

	@Override
	public void initListTrip() {
		tripDao.findAllTrip(new AsyncCallback<List<TripDto>>() {

			@Override
			public void onSuccess(List<TripDto> result) {

				List<TripModel> tripModels = new ArrayList<TripModel>();

				for (TripDto tripDto : result) {
					TripModel tripModel = new TripModel();
					tripModel.setId(tripDto.getId());
					tripModel.setName(tripDto.getName());
					tripModels.add(tripModel);
				}

				// maj de l'ihm
				eventBus.fireEvent(new InitListTripEvent(tripModels));
			}

			@Override
			public void onFailure(Throwable caught) {
				// nothing
			}
		});
	}

	@Override
	public void onCreateTrip(String tripName) {
		HashMap<String, String> parameters = new HashMap<String, String>();
		parameters.put(TwgConstants.PARAM_TRIPNAME, tripName);
		PlaceController pc = clientFactory.getPlaceController();
		Place place = new VoyagePlace(parameters);
		pc.goTo(place);
	}
}
